package com.chushouya.common.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * rsa工具类
 */
public abstract class RsaUtil {

    /**
     * rsa解密
     *
     * @param data   待解密的数据
     * @param prikey 私钥
     * @return 解密数据, utf8字符串
     */
    public static String decrypt(byte[] data, byte[] prikey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        KeySpec keySpec = new PKCS8EncodedKeySpec(prikey);
        PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(keySpec);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] bytes = cipher.doFinal(data);
        return new String(bytes, StandardCharsets.UTF_8);
    }

    /**
     * ras加密
     *
     * @param data   待加密的数据
     * @param pubKey 公钥
     * @return 加密后的数据，base64字符串
     */
    public static String encrypt(byte[] data, byte[] pubKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        KeySpec keySpec = new X509EncodedKeySpec(pubKey);
        PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(keySpec);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] bytes = cipher.doFinal(data);
        return Base64.encodeBase64String(bytes);
    }
}
